/*
 * Copyright (C) 2016-2017 AnStudio
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.astudio.lhasa.database.helpers;

import com.astudio.lhasa.database.beans.OfflineDictWord;
import com.astudio.lhasa.utils.TextHelper;

import org.litepal.crud.DataSupport;

import java.util.List;

public class OfflineDictManager {

    private static OfflineDictManager mInstance = null;

    public static final int OFFLINE_DICT_WORD_TYPE_SOURCE_CHN = 1;
    public static final int OFFLINE_DICT_WORD_TYPE_SOURCE_TBT = 2;

    private OfflineDictManager(){
    }

    public static OfflineDictManager getInstance() {
        if (mInstance == null) {
            synchronized (OfflineDictManager.class) {
                mInstance = new OfflineDictManager();
            }
        }

        return mInstance;
    }

    public void insertWord(String input, String translation) {
        OfflineDictWord bean = new OfflineDictWord();
        bean.setType(TextHelper.isTibetanCharacter(input) ?
                OFFLINE_DICT_WORD_TYPE_SOURCE_TBT : OFFLINE_DICT_WORD_TYPE_SOURCE_CHN);
        bean.setInput(input);
        bean.setTranslation(translation);
        bean.setLastUpdate(System.currentTimeMillis());
        bean.save();
    }

    public void deleteWord(String input) {
        DataSupport.deleteAll(OfflineDictWord.class, "input = ? ", input);
    }

    public OfflineDictWord queryDict(String input) {
        OfflineDictWord ret = null;

        List<OfflineDictWord> resultList =
                DataSupport.where("input = ? ", input).find(OfflineDictWord.class);

        if (resultList != null && resultList.size() > 0) {
            ret = resultList.get(0);
        }

        return ret;
    }

    public void upgradeWord(String input, String translation) {
        OfflineDictWord candidate = queryDict(input);
        if (candidate == null) {
            insertWord(input, translation);
        } else {
            candidate.setTranslation(translation);
            candidate.save();
        }

    }

    public void insertOrUpdate(String input, String translation) {
        OfflineDictWord queryResult = queryDict(input);
        if (queryResult == null) {
            insertWord(input, translation);
        } else {
            upgradeWord(input, translation);
        }
    }
}
